package com.dqhl.community.activity;

import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.dqhl.community.R;
import com.dqhl.community.base.BaseActivity;
import com.dqhl.community.util.Config;
import com.dqhl.community.util.Constant;
import com.dqhl.community.util.Dlog;
import com.dqhl.community.util.JsonUtils;
import com.dqhl.community.util.UserSaveUtil;
import com.dqhl.community.view.CircleImageView;
import com.dqhl.community.view.PictureSelectPopupWindow;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * Created by cheng on 2016/8/30.
 * 个人基本信息界面
 */
public class PersonalInfoActivity extends BaseActivity implements View.OnClickListener {

    private Context context;
    private ImageView ivTopBack;
    private TextView tvTopTitle;
    private CircleImageView ivHeadPortrait; // 头像
    private String photoPath; //
    private String strNickname;
    private String strSex;
    private static int REQUESTCODE_PICTURE = 100;
    private static int REQUESTCODE_CAMERA = 101;
    private TextView tv_nickname;
    private TextView tv_sex;
    private PictureSelectPopupWindow pictureSelectPopupWindow; // 照片选择popupwindow
    private LinearLayout ll_modify_nickname;
    private LinearLayout ll_modify_sex;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_info);
        context = this;
        registerBroadcastReceiver();
        initView();
        initData();
    }

    /**
     * 定义 BroadcastReceiver
     */
    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case Constant.ACTION_UPDATA_SUCCESS://修改昵称
                    tv_nickname.setText(intent.getStringExtra(Constant.NICKNAME));
                    break;
                case Constant.ACTION_UPDATE_SEX: //修改性别
                    strSex = intent.getStringExtra(Constant.SEX);
                    tv_sex.setText(strSex);
                    break;

            }
        }
    };

    /**
     * 注册广播
     */
    private void registerBroadcastReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.ACTION_UPDATA_SUCCESS);//修改昵称
        intentFilter.addAction(Constant.ACTION_UPDATE_SEX); //修改性别
        registerReceiver(receiver, intentFilter);
    }

    /**
     * 初始化数据
     */
    private void initData() {
        strNickname = spUserInfo.getString(Constant.NICKNAME, "");
        strSex = spUserInfo.getString(Constant.SEX, "");
        // 从SharedPreferences获取头像的路径
        photoPath = spUserInfo.getString(Constant.PHOTO_PATH, "");
        Dlog.e("PersonalInfoActivitySharedPreferences里头像路径：" + photoPath);
        if (photoPath != null && photoPath.length() > 0) {
            x.image().bind(ivHeadPortrait, Config.Api.base_img_url + photoPath);
        } else {
            //显示一个默认头像
            ivHeadPortrait.setImageResource(R.drawable.ic_no_head_portrait);
        }
        if (strNickname != null && strNickname.length() > 0) {
            tv_nickname.setText(strNickname);
        } else {
            tv_nickname.setText("修改昵称");
        }
        if (strSex != null && strSex.length() > 0) {
            tv_sex.setText(strSex);
        } else {
            tv_sex.setText("设置性别");
        }

    }

    /**
     * 初始化控件
     */
    private void initView() {
        ivTopBack = (ImageView) findViewById(R.id.iv_top_back);
        ivTopBack.setVisibility(View.VISIBLE);
        tvTopTitle = (TextView) findViewById(R.id.tv_top_title);
        tvTopTitle.setText(R.string.txt_personal_info);
        ivHeadPortrait = (CircleImageView) findViewById(R.id.iv_head_portrait);
        tv_nickname = (TextView) findViewById(R.id.tv_nickname);
        tv_sex = (TextView) findViewById(R.id.tv_sex);

        ll_modify_nickname = (LinearLayout) findViewById(R.id.ll_modify_nickname);
        ll_modify_sex = (LinearLayout) findViewById(R.id.ll_modify_sex);
        ll_modify_nickname.setOnClickListener(this);
        ll_modify_sex.setOnClickListener(this);

        ivTopBack.setOnClickListener(this);
        ivHeadPortrait.setOnClickListener(this);
        pictureSelectPopupWindow = new PictureSelectPopupWindow(this, pictureSelectItemsOnClick);
        pictureSelectPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                pictureSelectPopupWindow.backgroundAlpha(1.0f);
            }
        });
    }

    View.OnClickListener pictureSelectItemsOnClick = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.btn_take_photo:   // 调用系统相机
                    Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(camera, REQUESTCODE_CAMERA);
                    pictureSelectPopupWindow.dismiss();
                    break;
                case R.id.btn_pick_photo:   // 调取手机相册
                    Intent picture = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(picture, REQUESTCODE_PICTURE);
                    pictureSelectPopupWindow.dismiss();
                    break;
                case R.id.btn_cancel:   // 取消
                    pictureSelectPopupWindow.dismiss();
                    break;
            }
        }
    };

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_top_back:
                finish();
                break;
            case R.id.iv_head_portrait:
                pictureSelectPopupWindow.showAtLocation(findViewById(R.id.activity_personal_info), Gravity.BOTTOM, 0, 0);
                pictureSelectPopupWindow.backgroundAlpha(0.5f);
                break;
            case R.id.ll_modify_nickname:
                Bundle bundle = new Bundle();
                bundle.putString("nickname", strNickname);
                overlay(UpdataNickNameActivity.class, bundle);
                break;
            case R.id.ll_modify_sex:
                Bundle bundle2 = new Bundle();
                bundle2.putString("sex", strSex);
                overlay(UpdataSexActivity.class, bundle2);
                break;
        }
    }

    /**
     * 更换头像接口
     */
    private void upLoadHeadImg() {
        if ("".equals(photoPath)) {
            toast("头像为空");
        } else {
            showCustomLoadBar(R.string.loading);
            File head_img = new File(photoPath);
            final String userid = spUserInfo.getString(Constant.USERID, "");
            RequestParams params = new RequestParams(Config.Api.modifyHead);
            params.addBodyParameter("userid", userid);
            Dlog.e("userid:" + userid);
            if (head_img.isFile()) {
                Dlog.e("图片路径" + head_img);
                params.addBodyParameter("head", head_img);
            }
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    int errCode = JsonUtils.getErrCode(result);
                    Dlog.e(errCode + "GG头像修改" + result);
                    String data = JsonUtils.getInfo(result, "data");
                    if (errCode == 0) {
//                        toast("修改成功");
                        // 需要报头像的路径返回来，更新sp
                        String head = JsonUtils.getInfo(data, "head");
                        spUserInfo.edit().putString(Constant.PHOTO_PATH, head).apply();
//                        user.setHead(head);
//                        UserSaveUtil.saveUser(context, user);
                        sendModifyPhotoBroadCast();
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    hideCustomLoadBar();
                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {
                    hideCustomLoadBar();
                }
            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            if (resultCode == RESULT_OK) {
                if (requestCode == REQUESTCODE_PICTURE) {
                    Uri selectedImage = geturi(data);
                    String[] filePathColumns = {MediaStore.Images.Media.DATA};
                    Cursor c = this.getContentResolver().query(selectedImage, filePathColumns, null, null, null);
                    if (c != null) {
                        c.moveToFirst();
                        int columnIndex = c.getColumnIndex(filePathColumns[0]);
                        photoPath = c.getString(columnIndex);
                        Dlog.e("photoPath:" + photoPath);
                        c.close();
                        x.image().bind(ivHeadPortrait, photoPath);

                        upLoadHeadImg();
                    }

                } else if (requestCode == REQUESTCODE_CAMERA) {
                    String sdState = Environment.getExternalStorageState();
                    if (sdState.equals(Environment.MEDIA_MOUNTED)) {
                        Bundle bundle = data.getExtras();
                        if (bundle != null) {
                            //获取相机返回的数据，并转换为图片格式
                            Bitmap bitmap = (Bitmap) bundle.get("data");
                            if (bitmap != null) {
                                FileOutputStream fout = null;
                                File file = new File(Constant.photoPath);
                                if (!file.exists()) {
                                    file.mkdirs();// 创建文件夹
                                }
                                //生成随机数，命名图片
                                photoPath = Constant.photoPath + UUID.randomUUID().toString() + ".jpg";
                                try {
                                    fout = new FileOutputStream(photoPath);
                                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fout);
                                    Dlog.e("photoPath:" + photoPath);
                                    x.image().bind(ivHeadPortrait, photoPath);
                                    upLoadHeadImg();
                                } catch (FileNotFoundException e) {
                                    e.printStackTrace();
                                } finally {
                                    try {
                                        if (fout != null) {
                                            fout.flush();
                                            fout.close();
                                        }
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                    } else {
                        Dlog.e("sd card unmount");
                    }
                }
            }
        }
    }

    /**
     * 发送一个修改头像的广播
     */
    private void sendModifyPhotoBroadCast() {
        Intent intent = new Intent(Constant.ACTION_PHOTO_MODIFY);
        intent.putExtra(Constant.PHOTO_PATH, photoPath);
        sendBroadcast(intent);
    }

    /**
     * 解决小米部分手机调用系统相册失败
     *
     * @param intent
     * @return
     */
    public Uri geturi(android.content.Intent intent) {
        Uri uri = intent.getData();
        String type = intent.getType();
        if (uri.getScheme().equals("file") && (type.contains("image/"))) {
            String path = uri.getEncodedPath();
            if (path != null) {
                path = Uri.decode(path);
                ContentResolver cr = this.getContentResolver();
                StringBuffer buff = new StringBuffer();
                buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=")
                        .append("'" + path + "'").append(")");
                Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        new String[]{MediaStore.Images.ImageColumns._ID},
                        buff.toString(), null, null);
                int index = 0;
                for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
                    index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
                    // set _id value
                    index = cur.getInt(index);
                }
                if (index == 0) {
                    // do nothing
                } else {
                    Uri uri_temp = Uri
                            .parse("content://media/external/images/media/"
                                    + index);
                    if (uri_temp != null) {
                        uri = uri_temp;
                    }
                }
            }
        }
        return uri;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 注销广播
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
    }
}
